﻿using System;
using System.Collections.Generic;
using RK.Common;
using RK.Store.MetroSnake.Data;
using Windows.Storage;
using Windows.UI.Xaml.Controls;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace RK.Store.MetroSnake.UI
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class HighscorePage : RK.Store.MetroSnake.Common.LayoutAwarePage, IPossibleNavigationTargets
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="HighscorePage" /> class.
        /// </summary>
        public HighscorePage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            StorageFolder sourceFolder = ApplicationData.Current.RoamingFolder;

            //Read the highscore file
            GameDataContainer loadedContainer = null;
            StorageFile highscoreFile = await sourceFolder.GetOrReturnNull("GameScore.xml");
            if (highscoreFile == null)
            {
                loadedContainer = new GameDataContainer();
            }
            else
            {
                try
                {
                    //Try to load current score from roaming file
                    GameDataContainer highScore = await CommonUtil.DeserializeFromXmlFile<GameDataContainer>(highscoreFile);
                    if (highScore == null) { highScore = new GameDataContainer(); }
                    loadedContainer = highScore;
                }
                catch (Exception)
                {
                    //Any exception occurred while deserializing
                    loadedContainer = new GameDataContainer();
                }
            }

            //Update highscore file with given parameter
            GameScore newScore = navigationParameter as GameScore;
            if (newScore != null)
            {
                //Try to insert the score between the lines
                bool scoreInserted = false;
                for (int loop = 0; loop < loadedContainer.GameScores.Count; loop++)
                {
                    if (loadedContainer.GameScores[loop].TotalScore < newScore.TotalScore)
                    {
                        loadedContainer.GameScores.Insert(loop, newScore);
                        scoreInserted = true;
                        break;
                    }
                }

                //Append new score on the end
                if (!scoreInserted)
                {
                    loadedContainer.GameScores.Add(newScore);
                }

                //Remove items if there are too much now
                while (loadedContainer.GameScores.Count > GameDataContainer.GAME_SCORE_MAX)
                {
                    loadedContainer.GameScores.RemoveAt(GameDataContainer.GAME_SCORE_MAX);
                }
            }

            //Update ui data
            this.DataContext = loadedContainer;

            //Select new score element if it is in the list
            if ((newScore != null) &&
                (loadedContainer.GameScores.Contains(newScore)))
            {
                this.LstHighScore.SelectedItem = newScore;
            }

            //Save updated highscore to file again
            if (newScore != null)
            {
                StorageFile highscoreFileOut = await sourceFolder.CreateFileAsync("GameScore.xml", CreationCollisionOption.ReplaceExisting);
                await CommonUtil.SerializeToXmlFile(highscoreFileOut, loadedContainer);
            }
        }

        public bool CanNavigateToHighScore
        {
            get { return false; }
        }

        public bool CanNavigateToHelp
        {
            get { return false; }
        }

        public bool CanNavigateToNewGame
        {
            get { return true; }
        }

        public bool CanNavigateToComments
        {
            get { return false; }
        }
    }
}